const router = require('koa-router')()
const request = require('request');
const jsonwebtoken = require('jsonwebtoken')
const jwt = require('koa-jwt')
const { secret } = require('../config')
const axios = require('axios')
const { mp } = require('../config/index.js')
console.log(mp, 'wx')
router.prefix('/api')
const auth = jwt({ secret })
/**
 * 1. async是声明一个异步函数
 * 2. async返回一个promise   async function auto() {}   auto().then(res => {})
 * 3. await需要跟async搭配使用
 * 4. await后面一般跟一个promise    await axios.get('/')
 */

function fetchUrl(url) {
  return new Promise((resolve, reject) => {
    request(url, function(err, response, body) {
      console.log(response.statusCode, '状态吗')
      if (response.statusCode === 200) {
        resolve(JSON.parse(body))
      } else {
        reject()
      }
    })
  })
}


// 公司后台 await 后面跟promise
router.post('/getSession', async (ctx, next) => {
  const { code } = ctx.request.body;
  console.log("code: ", code)
  if(code) {
    const requestUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${mp.appid}&secret=${mp.appsecret}&js_code=${code}&grant_type=authorization_code`
    const data =  await fetchUrl(requestUrl)
    const token = jsonwebtoken.sign({ openid: data.openid }, secret)
    ctx.body = {
      code: 0,
      msg: 'success',
      openid: data.openid,
      token
    }
  } else {
    ctx.body = {
      code: 0,
      msg: 'code参数还未获取，请重新获取'
    }
  }
})

router.get('/test-get', async (ctx, next) => {
  ctx.body = {
    data: '测试信息'
  }
})
module.exports = router;